package com.aiyige.arouter;

import android.net.Uri;
import android.text.TextUtils;

import com.aiyige.BuildConfig;
import com.aiyige.MyApp;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.arouter.eventbus.EventCommunicatePageRouter;
import com.aiyige.arouter.eventbus.EventHomePageRouter;
import com.aiyige.arouter.eventbus.EventMainPageRouter;
import com.aiyige.arouter.util.RouterUtil;
import com.aiyige.im.SessionHelper;
import com.aiyige.model.Subject;
import com.aiyige.model.moment.entity.Moment;
import com.aiyige.model.tag.Tag;
import com.aiyige.page.discovery.model.ActivityData;
import com.aiyige.page.player.PlayerInfo;
import com.aiyige.trace.model.Trace;
import com.aiyige.trace.util.TraceUtil;
import com.aiyige.track.TrackEvent;
import com.aiyige.track.TrackUtil;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.StringUtils;
import com.alibaba.android.arouter.facade.Postcard;
import com.alibaba.android.arouter.launcher.ARouter;

import org.greenrobot.eventbus.EventBus;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.aiyige.track.TrackEvent.MY_BUY_LEARN_VIDEO_VIEW_DATE;
import static com.aiyige.track.TrackEvent.MY_BUY_LEARN_VIDEO_VIEW_DATE_LABEL;

/**
 * 爱一格-路由
 * Created by xiachao on 2017/11/24.
 */

public class Router {
    public static final EventBus eventBus = new EventBus();

    public static void registerRouterEventBus(Object o) {
        try {
            if (!eventBus.isRegistered(o)) {
                eventBus.register(o);
            }
        } catch (Exception e) {

        }
    }

    public static void unregisterRouterEventBus(Object o) {
        try {
            if (eventBus.isRegistered(o)) {
                eventBus.unregister(o);
            }
        } catch (Exception e) {

        }
    }

    public static boolean start(String router, Map<String, String> queryParams, Map<String, Object> webviewConfig, String traceId) {
        if (!TextUtils.isEmpty(traceId)) {
            TraceUtil.clear();
            try {
//                String momentId = Uri.parse(router).getQueryParameter("momentId");
//                momentId = TextUtils.isEmpty(momentId) ? "" : momentId;
                TraceUtil.push(Trace.newBuilder()
                        .target("")
                        .traceId(traceId)
                        .code(-1)
                        .build());
            } catch (Exception e) {

            }
        }
        return start(router, queryParams, webviewConfig);
    }

    public static boolean start(String router, String traceId) {
        if (!TextUtils.isEmpty(traceId)) {
            TraceUtil.clear();
            try {
                String momentId = Uri.parse(router).getQueryParameter("momentId");
                momentId = TextUtils.isEmpty(momentId) ? "" : momentId;
                TraceUtil.push(Trace.newBuilder()
                        .target(momentId)
                        .traceId(traceId)
                        .build());
            } catch (Exception e) {

            }
        }
        return start(router);
    }

    public static boolean start(String router, Map<String, Object> webviewConfig, String traceId) {
        if (!TextUtils.isEmpty(traceId)) {
            TraceUtil.clear();
            try {
                String momentId = Uri.parse(router).getQueryParameter("momentId");
                momentId = TextUtils.isEmpty(momentId) ? "" : momentId;
                TraceUtil.push(Trace.newBuilder()
                        .target(momentId)
                        .traceId(traceId)
                        .build());
            } catch (Exception e) {

            }
        }
        return start(router, webviewConfig);
    }


    public static boolean start(String router, Map<String, String> queryParams, Map<String, Object> webviewConfig) {
        try {
            Uri.Builder uriBuilder = Uri.parse(router).buildUpon();
            for (Map.Entry<String, String> entry : queryParams.entrySet()) {
                uriBuilder.appendQueryParameter(entry.getKey(), entry.getValue());
            }
            return start(uriBuilder.build().toString(), webviewConfig);
        } catch (Exception e) {
            return false;
        }
    }

    public static boolean start(String router) {
        return start(router, Collections.EMPTY_MAP);
    }

    public static boolean start(String router, Map<String, Object> webviewConfig) {
        try {
            if (TextUtils.isEmpty(router)) {
                return false;
            }
            Uri uri = Uri.parse(router);
            String scheme = uri.getScheme();
            if (TextUtils.isEmpty(scheme)) {
                scheme = "http";
                router = scheme + "://" + router;
                uri = Uri.parse(router);
            }
            if (scheme.toLowerCase().contains("http")) {
                return handleH5Router(uri, webviewConfig);
            }

            if (!scheme.trim().toLowerCase().equals(BuildConfig.AIYIGE_APP_SCHEME)) {
                return false;
            }


            String path = uri.getPath();
//            if (path.equals("/learn/detail_video_course")) {
//                path = ExRouter.VIDEO_COURSE_DETAIL;
//            }
            switch (path) {
                case ExRouter.RECOMMEND:
                    ARouter.getInstance()
                            .build(ARouterConfig.MainPage)
                            .withFlags(RouterUtil.FLAG_BRING_TO_FRONT)
                            .navigation();
                    eventBus.postSticky(EventMainPageRouter.newBuilder()
                            .jumpIndex(0)
                            .build());
                    eventBus.postSticky(EventHomePageRouter.newBuilder()
                            .jumpIndex(0)
                            .build());
                    break;
                case ExRouter.INDEX:
                    String channel = StringUtils.escapeEmptyString(uri.getQueryParameter("channel"));
                    EventMainPageRouter eventMainPageRouter = EventMainPageRouter.newBuilder()
                            .jumpIndex(0)
                            .build();
                    EventHomePageRouter eventHomePageRouter = EventHomePageRouter.newBuilder()
                            .jumpIndex(0)
                            .build();
                    switch (channel) {
                        case ExRouter.INDEX_CHANNEL_ATTENTION:
                            eventHomePageRouter.setJumpIndex(2);
                            break;
                        case ExRouter.INDEX_CHANNEL_HOTTEST:
                            eventHomePageRouter.setJumpIndex(1);
                            break;
                        default:
                            if (AccountUtil.isLogin()) {
                                List<Tag> tagList = AccountUtil.getCurrentUser().getAvocation();
                                if (!ListUtil.isEmpty(tagList)) {
                                    for (int i = 0; i < tagList.size(); ++i) {
                                        if (channel.equals(tagList.get(i).getId())) {
                                            eventHomePageRouter.setJumpIndex(3 + i);
                                            break;
                                        }
                                    }
                                }
                            }
                            break;
                    }
                    ARouter.getInstance()
                            .build(ARouterConfig.MainPage)
                            .withFlags(RouterUtil.FLAG_BRING_TO_FRONT)
                            .navigation();
                    eventBus.postSticky(eventMainPageRouter);
                    eventBus.postSticky(eventHomePageRouter);
                    break;
                case ExRouter.GLOBAL_SEARCH:
                    String keyword = StringUtils.escapeEmptyString(uri.getQueryParameter("keyword"));
                    ARouter.getInstance().build(ARouterConfig.GlobalSearchPage)
                            .withString("searchWord", keyword)
                            .navigation();
                    break;
                case ExRouter.PHOTO_DETAIL: {
                    String source = uri.getQueryParameter("source");
                    source = TextUtils.isEmpty(source) ? "" : source;
                    String resourceId = uri.getQueryParameter("resourceId");
                    resourceId = TextUtils.isEmpty(resourceId) ? "" : resourceId;
                    String momentId = uri.getQueryParameter("momentId");
                    momentId = TextUtils.isEmpty(momentId) ? "" : momentId;
                    String presetTidStr = uri.getQueryParameter("tid");
                    String presetCodeStr = uri.getQueryParameter("code");
                    Trace trace = TraceUtil.peek();
                    if (trace != null) {
                        if (TextUtils.isEmpty(presetTidStr) || TextUtils.isEmpty(presetCodeStr)) {
                            TraceUtil.push(Trace.newBuilder()
                                    .target(momentId)
                                    .traceId(trace.getTraceId())
                                    .code(trace.getCode() + 1)
                                    .build());
                        } else {
                            int code = 0;
                            try {
                                code = Integer.parseInt(presetCodeStr);
                            } catch (Exception e) {
                                code = trace.getCode() + 1;
                            }
                            TraceUtil.push(Trace.newBuilder()
                                    .target(momentId)
                                    .traceId(trace.getTraceId())
                                    .code(code)
                                    .build());

                        }
                    }
                    ARouter.getInstance()
                            .build(ARouterConfig.DetailPage)
                            .withString("momentId", momentId)
                            .withString("source", source)
                            .withString("resourceId", resourceId)
                            .navigation();


                    break;
                }
                case ExRouter.VIDEO_DETAIL: {
                    String source = uri.getQueryParameter("source");
                    source = TextUtils.isEmpty(source) ? "" : source;
                    String resourceId = uri.getQueryParameter("resourceId");
                    resourceId = TextUtils.isEmpty(resourceId) ? "" : resourceId;
                    String momentId = uri.getQueryParameter("momentId");
                    momentId = TextUtils.isEmpty(momentId) ? "" : momentId;
                    String presetTidStr = uri.getQueryParameter("tid");
                    String presetCodeStr = uri.getQueryParameter("code");
                    Trace trace = TraceUtil.peek();
                    if (trace != null) {
                        if (TextUtils.isEmpty(presetTidStr) || TextUtils.isEmpty(presetCodeStr)) {
                            TraceUtil.push(Trace.newBuilder()
                                    .target(momentId)
                                    .traceId(trace.getTraceId())
                                    .code(trace.getCode() + 1)
                                    .build());
                        } else {
                            int code = 0;
                            try {
                                code = Integer.parseInt(presetCodeStr);
                            } catch (Exception e) {
                                code = trace.getCode() + 1;
                            }
                            TraceUtil.push(Trace.newBuilder()
                                    .target(momentId)
                                    .traceId(trace.getTraceId())
                                    .code(code)
                                    .build());

                        }
                    }
                    ARouter.getInstance()
                            .build(ARouterConfig.DetailPage)
                            .withString("momentId", momentId)
                            .withString("source", source)
                            .withString("resourceId", resourceId)
                            .navigation();
                    break;
                }
                case ExRouter.REFUND_DETAIL: {
                    ARouter.getInstance()
                            .build(ARouterConfig.RefundApplyDetailPage)
                            .withString("refundId", uri.getQueryParameter("refundId"))
                            .withBoolean("isBuyer", false)
                            .navigation();
                    break;
                }
                case ExRouter.ORDER_DETAIL: {
                    boolean isBuyer = uri.getBooleanQueryParameter("isBuyer", false);
                    String orderId = uri.getQueryParameter("orderId");
                    ARouter.getInstance()
                            .build(ARouterConfig.OrderDetailPage)
                            .withBoolean("isBuyer", isBuyer)
                            .withString("orderId", orderId)
                            .navigation();
                    break;
                }

                case ExRouter.VIDEO_COURSE_DETAIL: {
                    String source = uri.getQueryParameter("source");
                    source = TextUtils.isEmpty(source) ? "" : source;
                    String resourceId = uri.getQueryParameter("resourceId");
                    resourceId = TextUtils.isEmpty(resourceId) ? "" : resourceId;
                    String momentId = uri.getQueryParameter("momentId");
                    momentId = TextUtils.isEmpty(momentId) ? "" : momentId;
                    String presetTidStr = uri.getQueryParameter("tid");
                    String presetCodeStr = uri.getQueryParameter("code");
                    Trace trace = TraceUtil.peek();
                    if (trace != null) {
                        if (TextUtils.isEmpty(presetTidStr) || TextUtils.isEmpty(presetCodeStr)) {
                            TraceUtil.push(Trace.newBuilder()
                                    .target(momentId)
                                    .traceId(trace.getTraceId())
                                    .code(trace.getCode() + 1)
                                    .build());
                        } else {
                            int code = 0;
                            try {
                                code = Integer.parseInt(presetCodeStr);
                            } catch (Exception e) {
                                code = trace.getCode() + 1;
                            }
                            TraceUtil.push(Trace.newBuilder()
                                    .target(momentId)
                                    .traceId(trace.getTraceId())
                                    .code(code)
                                    .build());

                        }
                    }
                    ARouter.getInstance()
                            .build(ARouterConfig.DetailPage)
                            .withString("momentId", uri.getQueryParameter("momentId"))
                            .withString("source", source)
                            .withString("resourceId", resourceId)
                            .navigation();
                    break;
                }

                case ExRouter.MY_ORDER:
                    ARouter.getInstance()
                            .build(ARouterConfig.MyOrderListPage)
                            .navigation();
                    break;
                case ExRouter.MY_PAGE:
                    ARouter.getInstance()
                            .build(ARouterConfig.MainPage)
                            .withFlags(RouterUtil.FLAG_BRING_TO_FRONT)
                            .navigation();
                    eventBus.postSticky(EventMainPageRouter.newBuilder()
                            .jumpIndex(3)
                            .build());
                    break;
                case "/tool/video_view":
                    List<PlayerInfo> playList = new ArrayList<>();
                    playList.add(PlayerInfo.newBuilder()
                            .cover(uri.getQueryParameter("poster"))
                            .isFree(true)
                            .path(uri.getQueryParameter("uri"))
                            .title("")
                            .build());
                    ARouter.getInstance()
                            .build(ARouterConfig.PlayerPage)
                            .withSerializable("playList", (Serializable) playList)
                            .navigation();
                    break;
                case ExRouter.HOME:
                    ARouter.getInstance()
                            .build(ARouterConfig.UserPage)
                            .withString("userId", uri.getQueryParameter("userId"))
                            .navigation();
                    break;
                case ExRouter.MY_COUPONS:
                    ARouter.getInstance()
                            .build(ARouterConfig.UserCouponPage)
                            .navigation();
                    break;
                case ExRouter.DRAW_COUPON_CENTER:
                    ARouter.getInstance()
                            .build(ARouterConfig.DrawCouponPage)
                            .navigation();
                    break;
                case ExRouter.NOTIFY_SYSTEMS:
                    ARouter.getInstance()
                            .build(ARouterConfig.SysMessagePage)
                            .navigation();
                    break;
                case ExRouter.NOTIFY_INTERACTS:
                    ARouter.getInstance()
                            .build(ARouterConfig.InteractMessagePage)
                            .navigation();
                    break;
                case ExRouter.NOTIFY_ORDERS:
                    ARouter.getInstance()
                            .build(ARouterConfig.OrderMessagePage)
                            .navigation();
                    break;
                case ExRouter.DISCOVERY_LIST:
                    ARouter.getInstance()
                            .build(ARouterConfig.MainPage)
                            .withFlags(RouterUtil.FLAG_BRING_TO_FRONT)
                            .navigation();
                    eventBus.postSticky(EventMainPageRouter.newBuilder()
                            .jumpIndex(1)
                            .build());
                    break;
                case ExRouter.DISCOVERY_VIDEO_COURSE:
                    ARouter.getInstance()
                            .build(ARouterConfig.LearnFilterPage)
                            .withString("subject", Moment.SUBJECT_VIDEO_COURSE)
                            .navigation();
                    break;
                case ExRouter.DISCOVERY_MAJOR_COURSE:
                    ARouter.getInstance()
                            .build(ARouterConfig.LearnFilterPage)
                            .withString("subject", Moment.SUBJECT_MAJOR_COURSE)
                            .navigation();
                    break;
                case ExRouter.DISCOVERY_SPECIAL_ZONE:
                    String zoneId = uri.getQueryParameter("zoneId");
                    if (!TextUtils.isEmpty(zoneId)) {
                        ARouter.getInstance().build(ARouterConfig.ActivityFilterPage)
                                .withParcelable("activityData", ActivityData.newBuilder()
                                        .sourceId(zoneId)
                                        .build())
                                .navigation();
                    }
                    break;
                case ExRouter.CHAT:
                    if (AccountUtil.isLogin()) {
                        ARouter.getInstance()
                                .build(ARouterConfig.MainPage)
                                .withFlags(RouterUtil.FLAG_BRING_TO_FRONT)
                                .navigation();
                        eventBus.postSticky(EventMainPageRouter.newBuilder()
                                .jumpIndex(2)
                                .build());
                        eventBus.postSticky(EventCommunicatePageRouter.newBuilder()
                                .jumpIndex(0)
                                .build());
                    } else {
                        ARouter.getInstance()
                                .build(ARouterConfig.LoginPage)
                                .navigation();
                    }
                    break;
                case ExRouter.CHAT_WITH:
                    String accid = StringUtils.escapeEmptyString(uri.getQueryParameter("accId"));
                    SessionHelper.startP2PSession(MyApp.getAppContext(), accid);
                    break;
                case ExRouter.EDIT_USER_INFO:
                    ARouter.getInstance()
                            .build(ARouterConfig.EditUserInfoPage)
                            .navigation();
                    break;
                case ExRouter.FANS_LIST:
                    ARouter.getInstance()
                            .build(ARouterConfig.FansPage)
                            .withString("userId", StringUtils.escapeEmptyString(uri.getQueryParameter("userId")))
                            .navigation();
                    break;
                case ExRouter.FOLLOWS_LIST:
                    ARouter.getInstance()
                            .build(ARouterConfig.FollowPage)
                            .withString("userId", StringUtils.escapeEmptyString(uri.getQueryParameter("userId")))
                            .navigation();
                    break;
                case ExRouter.DYNAMICS_SHOW:
                    ARouter.getInstance()
                            .build(ARouterConfig.DMPage)
                            .navigation();
                    break;
                case ExRouter.MY_COLLECTIONS:
                    ARouter.getInstance()
                            .build(ARouterConfig.MyFavoritePage)
                            .navigation();
                    break;
                case ExRouter.VIDEO_BUFFERS:
                    ARouter.getInstance()
                            .build(ARouterConfig.MyDownloadPage)
                            .navigation();
                    break;
                case ExRouter.VIEW_RECORDS:
                    ARouter.getInstance()
                            .build(ARouterConfig.MyViewPage)
                            .navigation();
                    break;
                case ExRouter.MY_TASKS:
                    ARouter.getInstance()
                            .build(ARouterConfig.MyBuyPage)
                            .navigation();
                    break;
                case ExRouter.MY_WALLET:
                    ARouter.getInstance()
                            .build(ARouterConfig.WalletHomePage)
                            .navigation();
                    break;
                case ExRouter.MY_SELL:
                    ARouter.getInstance()
                            .build(ARouterConfig.MySellPage)
                            .navigation();
                    break;
                case ExRouter.ORDERS_MANAGER:
                    ARouter.getInstance()
                            .build(ARouterConfig.OrderManagerPage)
                            .navigation();
                    break;

                case ExRouter.GOODS_MANAGER:
                    ARouter.getInstance()
                            .build(ARouterConfig.MMPage)
                            .navigation();
                    break;
                case ExRouter.CUSTOMERS_MANAGER:
                    ARouter.getInstance()
                            .build(ARouterConfig.CustomerManagementListPage)
                            .navigation();
                    break;
                case ExRouter.PENDING_PAYMENTS_MANAGER:
                    ARouter.getInstance()
                            .build(ARouterConfig.WaitReceiveMoneyListPage)
                            .navigation();
                    break;
                default: {
                    String h5Router = convertAppRouterToH5Router(router);
                    if (TextUtils.isEmpty(h5Router)) return false;
                    Uri h5Uri = Uri.parse(h5Router);
                    return handleH5Router(h5Uri, Collections.EMPTY_MAP);
                }
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 从已买跳转到详情
     *
     * @param moment
     */
    public static void start(Moment moment) {
        Moment recordMoment = new Moment(moment);
        if (recordMoment != null && !TextUtils.isEmpty(recordMoment.getSubject())
                && recordMoment.getSubject().equals(Subject.video_course)) {
            recordMoment.getMineBackup().setBuyed(1);
//                        ARouter.getInstance().build(ARouterConfig.DetailPage).withObject("moment", recordMoment).navigation();
            String howLong = TrackUtil.getHowLong(recordMoment.getOnsellTime());
            if (!TextUtils.isEmpty(howLong)) {
                HashMap<String, String> hashMap = new HashMap<>();
                hashMap.put("time_distance", howLong);
                TrackEvent trackEvent = new TrackEvent();
                trackEvent.sendEvent(MyApp.getAppContext(), MY_BUY_LEARN_VIDEO_VIEW_DATE,
                        MY_BUY_LEARN_VIDEO_VIEW_DATE_LABEL, hashMap);
            }
            ARouter.getInstance().build(ARouterConfig.DetailPage).withString("momentId", recordMoment.getId()).withBoolean("isMyBuy", true).navigation();
        } else {
            if (recordMoment != null) {
                Map<String, String> params = new HashMap<>();
                params.put("_from", "study");
                Router.start(recordMoment.getRouter(), params, Collections.EMPTY_MAP);
            }
        }
    }


    /**
     *
     *
     *
     */
    public static void startAiyigeH5(String router) {
        Map<String, String> params = new HashMap<>();
        params.put("_from", "study");
        Router.start(router, params, Collections.EMPTY_MAP);
    }


    public static String generateUserPageRouter(String userId) {
        return BuildConfig.AIYIGE_APP_SCHEME + "://" + BuildConfig.AIYIGE_APP_ROUTER_HOST + "/mine/user_center?userId=" + (TextUtils.isEmpty(userId) ? "" : userId);
    }


    private static String convertAppRouterToH5Router(String appRouter) {
        try {
            return BuildConfig.AIYIGE_H5_SCHEME + appRouter.trim().substring(BuildConfig.AIYIGE_APP_SCHEME.length());
        } catch (Exception e) {
            return "";
        }
    }


    private static boolean handleH5Router(Uri uri, Map<String, Object> webviewConfig) {
        try {
            Postcard postcard = ARouter.getInstance()
                    .build(ARouterConfig.WebViewPage)
                    .withString("url", uri.toString());
            for (Map.Entry<String, Object> entry : webviewConfig.entrySet()) {
                if (entry.getValue() instanceof String) {
                    postcard.withString(entry.getKey(), (String) entry.getValue());
                } else if (entry.getValue() instanceof Boolean) {
                    postcard.withBoolean(entry.getKey(), (Boolean) entry.getValue());
                } else {
                    postcard.withObject(entry.getKey(), entry.getValue());
                }
            }
            postcard.navigation();
            return true;
        } catch (Exception e) {
            return false;
        }

    }
}
